<?php
/**
 * Created by bianquan
 * CommonUser: ZhuYunlong
 * Email: 920200256@qq.com
 * Date: 2019/1/13
 * Time: 10:46
 */

namespace app\admin\logic\auth;

use app\admin\cache\RoleAuthCache;
use app\admin\logic\RestLogic;
use app\admin\model\auth\Admin as AdminModel;
use app\admin\service\PermissionService;
use app\lib\AuthErrorLock;
use app\lib\exception\AuthException;
use app\lib\exception\LoginException;
use app\lib\exception\ParameterException;
use app\lib\exception\ResourcesException;
use Doctrine\Common\Annotations\AnnotationReader;
use think\annotation\Inject;

class Admin extends RestLogic
{

    /**
     * @Inject()
     * @var \app\admin\model\auth\Admin
     */
    protected $model;

    /**
     * 管理员登录操作
     * @return AdminModel
     * @throws ParameterException
     * @throws ResourcesException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws LoginException
     * @throws AuthException
     */
    public function handleLogin() {
        $captcha = $this->request->post('captcha');
        if(!captcha_check($captcha)){
            // 验证失败
            throw new LoginException('验证码错误');
        }
        $username = $this->request->post('username');
        AuthErrorLock::instance($username)->check();
        /** @var \app\admin\model\auth\Admin $user */
        $user = $this->model->where('admin_name', '=', $username)
            ->find();
        if ($user === null) {
            AuthErrorLock::instance()->incrementError();
            throw new ResourcesException('账户不存在');
        }
        $password = $this->request->post('password');
        if (md5($password) !== $user->password) {
            AuthErrorLock::instance()->incrementError();
            throw new ParameterException('密码不正确');
        }
        // 生成权限key缓存
        RoleAuthCache::instance($user->role_id)->saveCache($user->role_id);
        // 生成token
        $user->token = Token::generateToken($user);
        return $user;
    }


    /**
     * 获取管理员列表
     * @return \think\Collection
     * @throws \think\db\exception\DbException
     */
    public function getList() {
        $query = $this->model->newQuery();
        $name = $this->getQuery('name');
        if ($name) {
            $query->where('admin_name', 'like', "%$name%");
        }
        return $this->handleGetList($query);
    }

    /**
     * 获取编辑表单
     */
    protected function setForm()
    {
        $this->form = [
            'admin_name' => input('admin_name'),
            'role_id' => input('role_id')
        ];
        $password = trim(input('password'));
        if (!empty($password)) {
            $this->form['password'] = md5($password);
        }
    }

    /**
     * 修改用户密码
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws ParameterException
     * @throws AuthException
     */
    public function changePassword() {
        $password = trim(input('newPassword'));
        $newPassword = trim(input('newPassword2'));
        if ($password !== $newPassword) {
            throw new ParameterException('两次密码输入不一致');
        }
        $admin = Token::instance()->admin();
        if ($admin->password !== md5(trim(input("oldPassword")))) {
            throw new AuthException('密码输入错误');
        }

        $admin->password = md5($password);
        $admin->save();
        return true;
    }

    /**
     * 刷新缓存
     * @throws \ReflectionException
     * @throws \app\lib\exception\DevException
     * @throws \Doctrine\Common\Annotations\AnnotationException
     */
    public function refreshCache() {
        // 刷新系统接口注解
        $service = new PermissionService(app());
        $service->boot(new AnnotationReader());
        $service->scanControllerDirs();

        // 刷新当前管理员权限缓存
        RoleAuthCache::instance()->saveCache(Token::instance()->getRoleID());
    }

}